﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using System.Diagnostics;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace FunctionPoint.Services
{
    public class TfsService : ITfsService
    {
        #region ITfsService Implementation
        public Microsoft.TeamFoundation.Client.TfsTeamProjectCollection TeamProjectCollection
        {
            get;
            set;
        }

        public Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore WorkItemStore
        {
            get;
            set;
        }

        public Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer VersionControlServer
        {
            get;
            set;
        }

        public Microsoft.TeamFoundation.Build.Client.IBuildServer BuildServer
        {
            get;
            set;
        }

        public void RefreshCache()
        {
            TeamProjectCollection.EnsureAuthenticated();
            WorkItemStore.RefreshCache();
        }

        #endregion


        #region Constructor
        
        public TfsService(string tfsServerUrl)
        {
            TeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
                   new Uri(tfsServerUrl), new UICredentialsProvider());

            TeamProjectCollection.EnsureAuthenticated();
            _authorizedIdentity = TeamProjectCollection.AuthorizedIdentity;
            Debug.WriteLine(String.Format("Connected to TFS collection {0} as {1}", TeamProjectCollection.Name, TeamProjectCollection.AuthorizedIdentity.DisplayName));

            WorkItemStore = (WorkItemStore) TeamProjectCollection.GetService(typeof(WorkItemStore));
            VersionControlServer = (VersionControlServer)   TeamProjectCollection.GetService(typeof(VersionControlServer));
            BuildServer = (IBuildServer)    TeamProjectCollection.GetService(typeof(IBuildServer));
        }

        #endregion

        private Microsoft.TeamFoundation.Framework.Client.TeamFoundationIdentity _authorizedIdentity;

        public Microsoft.TeamFoundation.Framework.Client.TeamFoundationIdentity AuthorizedIdentity
        {
            get { return AuthorizedIdentity; }
        }
    }
}
